require "rexml/document" 
class MsgFromWxesController < ApplicationController
  skip_before_filter :verify_authenticity_token, :only => [:create]
  before_action :set_msg_from_wx, only: [:show, :edit, :update, :destroy]

  # GET /msg_from_wxes
  # GET /msg_from_wxes.json
  def index
    #@msg_from_wxes = MsgFromWx.all
    p "**************************"
    p @str = params[:echostr]
    p "**************************"

    render :layout => false

  end

  # GET /msg_from_wxes/1
  # GET /msg_from_wxes/1.json
  def show

  end

  # GET /msg_from_wxes/new
  def new
    @msg_from_wx = MsgFromWx.new
  end

  # GET /msg_from_wxes/1/edit
  def edit
  end

  # POST /msg_from_wxes
  # POST /msg_from_wxes.json
  def create
    #@msg_from_wx = MsgFromWx.new(msg_from_wx_params)

    @msg_from_wx = request.body.read

    logger.info @msg_from_wx

#   @post = Post.new(post_params)
   
    source = @msg_from_wx
    doc = REXML::Document.new(source)

    #消息拆包
    incoming_msg = Message.new
    @to_user_name     = doc.root.elements["ToUserName"].text
    incoming_msg.from_user_name   = doc.root.elements["FromUserName"].text
    incoming_msg.create_time      = doc.root.elements["CreateTime"].text
    incoming_msg.msg_type         = doc.root.elements["MsgType"].text

    case incoming_msg.msg_type

    when "event"
      msg_event = doc.root.elements["Event"].text
      if msg_event = "subscribe"
        p "新用户"
        reply_xml = "new_user"
        @reply_msg = "回复\"#姓名\"告诉我们您是谁？\n\n点我可以看到我们的婚纱照。"
      end

    when "text"
      incoming_msg.content = doc.root.elements["Content"].text
      if incoming_msg.content =~ /^#/
        p "查找姓名是否存在"
        name_exits = GuestName.find_by_from_user_name(incoming_msg.from_user_name)

        if name_exits == nil
          new_user = GuestName.new
          new_user.from_user_name = incoming_msg.from_user_name
          real_name = incoming_msg.content.split('#')
          new_user.real_name = real_name[1]
          new_user.save
          reply_xml = "name_saved"
          @reply_msg = "欢迎您，#{new_user.real_name}!\n\n您的祝福是我们最珍贵的礼物！\n\n您现在可以编辑您的祝福发送给我们。\n\n也可以使用快速回复：\n\n回复“1”：海枯石烂同心永结，地阔天高比翼齐飞\n\n回复“2”：金屋笙歌偕彩凤，洞房花烛喜乘龙\n\n回复“3”：敬祝百年好合，永结同心！\n\n回复“4”：让这缠绵的诗句，敲响幸福的钟声。祝你们永远幸福恩爱。\n\n回复“5”：愿你俩恩恩爱爱，意笃情深，此生爱情永恒，爱心与日俱增！"
        else
          p "更新姓名"
          real_name = incoming_msg.content.split('#')
          name_exits.real_name = real_name[1]
          name_exits.save
          reply_xml = "name_changed"
          @reply_msg = "欢迎您，#{name_exits.real_name}!\n\n您的祝福是我们最珍贵的礼物！\n\n您现在可以编辑您的祝福发送给我们。\n\n也可以使用快速回复：\n\n回复“1”：海枯石烂同心永结，地阔天高比翼齐飞\n\n回复“2”：金屋笙歌偕彩凤，洞房花烛喜乘龙\n\n回复“3”：敬祝百年好合，永结同心！\n\n回复“4”：让这缠绵的诗句，敲响幸福的钟声。祝你们永远幸福恩爱。\n\n回复“5”：愿你俩恩恩爱爱，意笃情深，此生爱情永恒，爱心与日俱增！"
        end

      elsif incoming_msg.content =~ /帮助/
        reply_xml = "help"

      elsif incoming_msg.content == "1"
        incoming_msg.content = "海枯石烂同心永结，地阔天高比翼齐飞!"
        incoming_msg.save
        reply_xml = "thanks"

      elsif incoming_msg.content == "2"
        incoming_msg.content = "金屋笙歌偕彩凤，洞房花烛喜乘龙!"
        incoming_msg.save
        reply_xml = "thanks"

      elsif incoming_msg.content == "3"
        incoming_msg.content = "敬祝百年好合，永结同心！"
        incoming_msg.save
        reply_xml = "thanks"

      elsif incoming_msg.content == "4"
        incoming_msg.content = "让这缠绵的诗句，敲响幸福的钟声。祝你们永远幸福恩爱。"
        incoming_msg.save
        reply_xml = "thanks"

      elsif incoming_msg.content == "5"
        incoming_msg.content = "愿你俩恩恩爱爱，意笃情深，此生爱情永恒，爱心与日俱增！"
        incoming_msg.save
        reply_xml = "thanks"

      else
        name_exits = GuestName.find_by_from_user_name(incoming_msg.from_user_name)
        if name_exits == nil
          reply_xml = "ask_for_name"
        else
          reply_xml = "thanks"
        end
        incoming_msg.save
      end

    end


=begin
    respond_to do |format|
      if @msg_from_wx.save
        format.html { redirect_to @msg_from_wx, notice: 'Msg from wx was successfully created.' }
        format.json { render action: 'show', status: :created, location: @msg_from_wx }
      else
        format.html { render action: 'new' }
        format.json { render json: @msg_from_wx.errors, status: :unprocessable_entity }
      end
    end
=end

    #render :text => "test"
    @respond_msg = incoming_msg
    #render "echo", :formats => :xml, :layout => false
    render reply_xml, :formats => :xml, :layout => false
  end

  # PATCH/PUT /msg_from_wxes/1
  # PATCH/PUT /msg_from_wxes/1.json
  def update
    respond_to do |format|
      if @msg_from_wx.update(msg_from_wx_params)
        format.html { redirect_to @msg_from_wx, notice: 'Msg from wx was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @msg_from_wx.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /msg_from_wxes/1
  # DELETE /msg_from_wxes/1.json
  def destroy
    @msg_from_wx.destroy
    respond_to do |format|
      format.html { redirect_to msg_from_wxes_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_msg_from_wx
      @msg_from_wx = MsgFromWx.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def msg_from_wx_params
      params.require(:msg_from_wx).permit(:xml_msg)
    end
end
